//
//  NetWorkingHandle.m
//  6.1知识点UI22_NSURLSession
//
//  Created by dingcong on 16/6/1.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "NetWorkingHandle.h"
#import "MD5Handler.h"
#import "SandBoxStore.h"
@interface NetWorkingHandle()<NSURLSessionDataDelegate, NSURLSessionDelegate>
@property (nonatomic, strong)NSMutableData *mData;

@end
@implementation NetWorkingHandle

#pragma mark - public
- (void)netWorkingHandlerGetWithURL:(NSString *)string
                         completion:(void(^)(id result, NSData *data, NSURLResponse *response, NSError *error))completion
{
    
    NSURL *url = [self encodingURLWithString:string];
    
    NSString *strMD5 = [MD5Handler stringFromMD5:string];
    
    
    
    
    //核心API
    NSURLSession *session = [NSURLSession sharedSession];
    //验证线程 1为主线程
    NSLog(@"%@", [NSThread currentThread]);
    
    // 向session中添加任务(data)
  NSURLSessionDataTask *dataTast = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
    {
//        验证线程
        SandBoxStore *sandBox = [SandBoxStore sharedSandBoxStore];
        
        if (data != nil)
        {
            NSLog(@"%@", [NSThread currentThread]);
            //        NSLog(@"%@", data);
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            /*存入沙盒*/
            
            
            
            [sandBox storeByArchiverWithObject:result forkey:strMD5];
            if ([sandBox storeByArchiverWithObject:result forkey:strMD5]) {
                NSLog(@"存储至沙盒成功!");
            }
            
            
            //服务器先返回一个包  再响应(传输)数据
            //        NSLog(@"%@", response);
            
            //进入主线程, block回调
            
            dispatch_async(dispatch_get_main_queue(), ^
            {
                //            回调
                completion(result, data, response, error);
            });
        }
        
    }];
    
    
    
    
    
    //开始任务
    [dataTast resume];
    
    
}

- (void)netWorkingHandleGetWithURL:(NSString *)string{
    
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    
    
    NSURL *url = [self encodingURLWithString:string];
    //核心API
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
    
    //向session中添加任务
   NSURLSessionDataTask *task = [session dataTaskWithURL:url];
    
    
    //开始任务
    
    [task resume];
    
}
#pragma mark - private
- (NSURL *)encodingURLWithString:(NSString *)string
{
//    NSString *decode = [string stringByRemovingPercentEncoding];
    
    
    
    
    //核心API
    
    
    
    
   NSString *encodingStr = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSURL *url = [NSURL URLWithString:encodingStr];
    return url;
    
}

#pragma mark - dataTask delegate

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler
/** 收到服务器响应时,调用此方法 */
{
    //初始化(可以不再这里写, 可以看block怎么调用)
    self.mData = [NSMutableData data];
    
    //调用block
    completionHandler (NSURLSessionResponseAllow);//任务继续 会跳到receivedata方法
    NSLog(@"%s, %@", __func__, [NSThread currentThread]);
    
    
    
    
    
}
/* 从服务器接收到数据, 调用此方法, 此方法根据数据的大小, 可能会调用多次( 多次要拼接) (任务继续的方法)*/
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
    
    [self.mData appendData:data];
    
    NSLog(@"%s, %@", __func__, [NSThread currentThread]);
    
}

#pragma mark - Task delegate
/* 当任务完成之后 调用此协议方法*/
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    //解析数据
    id result = [NSJSONSerialization JSONObjectWithData:self.mData options:NSJSONReadingMutableContainers error:nil];
    //看线程
//    NSLog(@"%s, %@", __func__, [NSThread currentThread]);
    //通过delegate 回调数据.
    if ([self.delegate respondsToSelector:@selector(didCompleteWithJSONResult:receiveData:)])
    {
        
        
        //向主线程添加任务.
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.delegate didCompleteWithJSONResult:result receiveData:self.mData];
        });
        
    }
    
    
}


#pragma mark - POST

- (void)netWorkingHandlePostURL:(NSString *)string httpBody:(NSString *)body
        completion:(void(^)(id result, NSData *data, NSURLResponse *response, NSError *error))completion{

    
    NSURL *url = [NSURL URLWithString:string];
    NSMutableURLRequest *mrequest = [NSMutableURLRequest requestWithURL:url];
     NSURLSession *session = [NSURLSession sharedSession];
    //核心API
    
    //httpMethod
    mrequest.HTTPMethod = @"POST";
    
    //HTTPbODY
    mrequest.HTTPBody = [body dataUsingEncoding:NSUTF8StringEncoding];
   
    //会话添加任务
   NSURLSessionDataTask *dataTask =  [session dataTaskWithRequest:mrequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
    {
        //解析
        if (data)
        {
            
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            //向主线程中, 分配任务
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(result, data, response, error);
            });
        }
        
        
    }];
    
    
    //开始任务
    [dataTask resume];
    
}

- (void)netWorkingHandlePostWithURL:(NSString *)string httpBody:(NSString *)body{
    
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:string]];
    
    request.HTTPMethod = @"POST";
    request.HTTPBody = [body dataUsingEncoding:NSUTF8StringEncoding];
    //核心API
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
    
    //添加任务
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"数据1:%@", result);
        });

        
    }];
    [dataTask resume];
    
}



@end
